package com.export.netty;

import com.rlyy.aibase.os.service.Link;
import com.rlyy.aibase.utils.base.Box;
import com.rlyy.aibase.utils.base.MapNode;
import com.rlyy.aibase.utils.base.ThinkException;
import com.rlyy.aibase.view.key.APIKey_Enum;
import common.entity.ReflexHandler;
import common.exec.BaseException;
import common.exec.RsjIllegalArgueException;
import common.exec.RsjServiceWarnException;
import common.util.BoxUtil;
import common.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Component
public class BaseLink implements Link {
    protected static final Logger logger = LoggerFactory.getLogger(BaseLink.class);


    @Autowired
    private Map<String, ReflexHandler> handlerMapping;


    @Override
    public Box excute(Box in) throws ThinkException {
        try {
            ReflexHandler handler = handlerMapping.get(in.getApi());
            if (handler == null) {
                return new Box().setError("Api不存在");
            }

            Box box = (Box)handler.getMethod().invoke(handler.getBean(),in);

            return box;
        }
        // 校验异常
        catch (RsjIllegalArgueException e) {
            return BoxUtil.errorBox(in, e.getMessage());
        }
        // 业务异常
        catch (BaseException e) {
            return handlerBase(in, e);
        }
        // 框架异常
        catch (ThinkException e) {
            return handlerThink(in, e);
        }
        catch (InvocationTargetException targetException){
            Throwable t = targetException.getTargetException();
            if(t instanceof RsjIllegalArgueException){
                return BoxUtil.errorBox(in,t.getMessage());
            }
            if(t instanceof BaseException){
                return handlerBase(in, (BaseException) t);
            }
            if(t instanceof ThinkException){
                return handlerThink(in, (ThinkException) t);
            }
            return handlerException(in, targetException);
        }
        // 整体异常
        catch (Exception e) {
            return handlerException(in, e);
        } catch (Error e) {
            return handlerError(in, e);
        }
    }





    public Box handlerError(Box in, Error e) {
        // TODO error 处理
        logger.error("invoke--->" + in.getApi() + " error "
                + ", arguments is " + in.toJson(), e);
        return BoxUtil.errorBox(in, "服务器忙");
    }

    private Box handlerException(Box in, Exception e) {
        String errorCode = UUIDUtil.getUUID();
        loggerError(in, e, errorCode);
        return BoxUtil.errorBox(in, "服务器忙");
    }

    private Box handlerThink(Box in, ThinkException e) {
        String errorCode = UUIDUtil.getUUID();
        loggerError(in, e, errorCode);
        Box box = BoxUtil.errorBox(in, e.getMessage()).putMapNode(APIKey_Enum.EXCEPT.getKey(), e.toMapNode());
        logger.error(box.toJson());
        HashMap<String, String> jsonError = (HashMap<String, String>) box.toMap().get("_$except_");
        String $msg = jsonError.get("$msg");

        return BoxUtil.errorBox(in, "服务器忙");
    }

    private Box handlerBase(Box in, BaseException e) {
        String errorCode = UUIDUtil.getUUID();
        loggerError(in, e, errorCode);
        if (e instanceof RsjServiceWarnException) {// 前台处理逻辑，code码不同
            return BoxUtil.warnsBox(in, e.getMessage());
        }
        return BoxUtil.errorBox(in, "错误:" + errorCode + ":" + e.getMessage());
    }

    private void loggerError(Box in, Exception e, String errorCode) {
        logger.error("invoke--->" + in.getApi() + " error "
                + ", arguments is " + in.toJson() + ","
                + "UUID=" + errorCode, e);
    }

    protected Box executeLink(Box box) throws SQLException {
        return null;
    }

    private static MapNode map = new MapNode();

    static {
        map.putNode("rsj.api.loginAuth.Login", "用户管理:登录:1");
        map.putNode("rsj.api.user.UserInsert", "用户管理:新增用户:2");
        map.putNode("rsj.api.user.UserUpdate", "用户管理:修改用户:3");
        map.putNode("rsj.api.user.UserDel", "用户管理:删除用户:4");
        map.putNode("rsj.api.user.UserUpdatePass", "用户管理:修改密码:3");
        map.putNode("rsj.api.product.DoProductInsert", "产品管理:新增产品:2");
        map.putNode("rsj.api.product.DoProductUpdate", "产品管理:修改产品:3");
        map.putNode("rsj.api.orgp.DoApplyProd", "产品管理:申请产品:2");
        map.putNode("rsj.api.product.DoSaveCollProd", "产品管理:收藏产品:3");
        map.putNode("rsj.api.product.GetFilOpeToken", "产品管理:下载产品:5");
        map.putNode("rsj.api.org.OrgInsert", "机构管理:增加机构:2");
        map.putNode("rsj.api.org.OrgUpdate", "机构管理:修改机构:3");
        map.putNode("rsj.api.user.RoleInsert", "角色管理:角色新增:2");
        map.putNode("rsj.api.orgp.RechargeInsert", "运营工作平台:充值维护:2");


    }
}
